package com.itheima.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Dto.SetmealDto;
import com.itheima.common.CustomException;
import com.itheima.dao.SetmealMapper;
import com.itheima.pojo.Dish;
import com.itheima.pojo.Setmeal;
import com.itheima.pojo.SetmealDish;
import com.itheima.service.SetmealDishService;
import com.itheima.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    //添加
    @Transactional
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);

        List<SetmealDish> list = setmealDto.getSetmealDishes();
        list.stream().map((item) -> {
//            item.setDishId(item.getDishId());
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(list);

    }


    @Transactional
    //删除
    @Override
    public void deletedWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(Setmeal::getId,ids);
        wrapper.eq(Setmeal::getStatus,1);

        int count = this.count(wrapper);

        if (count>0){
            throw new CustomException("套餐正在售卖，不能删除！");
        }
            this.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.in(SetmealDish::getDishId,ids);

        setmealDishService.remove(wrapper1);

    }

    @Override
    public SetmealDto getByIdWithDish(Long id) {
//        根据ID查询菜品的基本信息
        Setmeal byId = this.getById(id);
//        从SetmealDish表根据菜品的ID查询套餐菜品列表数据
        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SetmealDish::getId,byId.getId());
        List<SetmealDish> list = setmealDishService.list(wrapper);
//      将setmeal的属性拷贝到setmealDto中
        SetmealDto setmealDto = new SetmealDto();

        BeanUtils.copyProperties(byId,setmealDto);
    //    组装数据并返回(设置flavors)

        setmealDto.setSetmealDishes(list);
        return setmealDto;

    }


}
